package com.macro.mall.portal.util;


import com.alibaba.fastjson.JSONObject;
import com.macro.mall.portal.dto.Address;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author：hwh
 * @Description:
 * @name：AddressUtil
 * @Date：2024/10/22 21:56
 */
@Component
public class AddressUtil {

    private static final String HOST = "https://kzaddress2.market.alicloudapi.com";
    private static final String PATH = "/api/address/parse";
    private static final String METHOD = "POST";


    private static final String appCode= "25f8973b538d4e1791984ef14928318d";

    private static final Logger logger = LoggerFactory.getLogger(AddressUtil.class);

    public Address recognition(String  address) {
        // 输入检查
        if (address == null ||  address.isEmpty()) {
            throw new RuntimeException("输入的地址不能为空或无效。");
        }

        String addressString = address;

        // API 请求头设置
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appCode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        // 请求体设置
        Map<String, String> bodys = new HashMap<>();
        bodys.put("address", addressString);

        try {
            // 发送 POST 请求
            HttpResponse response = HttpUtils.doPost(HOST, PATH, METHOD, headers, new HashMap<>(), bodys);

            // 检查响应状态码
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("API请求失败，状态码: " + response.getStatusLine().getStatusCode());
            }

            String responseString = EntityUtils.toString(response.getEntity());
            return parseResponse(responseString);
        } catch (Exception e) {
            logger.error("地址识别失败", e); // 使用日志记录异常
            throw new RuntimeException("地址识别失败: " + e.getMessage());
        }
    }

    private Address parseResponse(String responseString) {
        JSONObject jsonObject = JSONObject.parseObject(responseString);
        Integer code = jsonObject.getInteger("code");

        // 检查 API 返回的状态码
        if (code != 200) {
            throw new RuntimeException("API错误，代码: " + code);
        }

        // 获取数据部分
        JSONObject data = jsonObject.getJSONObject("data");
        if (data == null) {
            throw new RuntimeException("响应中未找到数据。");
        }

        // 创建地址对象并填充数据
        Address address = new Address();
        address.setPostCode(data.getString("zipCode"));
        address.setProvince(data.getString("province"));
        address.setCity(data.getString("city"));
        address.setPhoneNumber(data.getString("mobile"));
        address.setName(data.getString("name"));
        address.setDetailAddress(data.getString("detail"));
        address.setRegion(data.getString("area"));

        return address;
    }
}
